define(function(require, exports, module) {
//	//将该页面路径上的&&flag=true去掉，防止刷新该页面的时候有该参数
//	var url=location.href;
//	var index=url.indexOf("&");
//	//如果在地址栏能找到"&"，那么重新请求该页面
//	if(index!=-1){
//		location.href=url.substring(0,index);
//	}
	
	var $ = require('jquery');
	var List = require('../util/list');
	require('../util/getURL.js');
	require('jbox');
	require('spin/1.3/spin.js');
	require('artTemplate/artTemplate/2.0.1/template.js');
	require('jquery/jquery-form/1.0.0/jquery.form.js');
	require('jquery/jquery-json/2.4.0/jquery.json.js');
	require('jquery/jquery-timeago/1.3.0/jquery.timeago.js');
	require('jquery/jquery-validation/1.11.0/jquery.validate');
	require('../util/tinymce-page.js');
	
	var flot = require('flot/flotr2');

	
	exports.options = {
		listLink : '',
		listParams : '',
		pageLink : '',
		pageParams : ''
	};
	var uid='';
	var isAttention="";
	var pida = UrlParm.parm("id");
	if($g_user.login == 'true'){
		uid = ''+$g_user.id;
	}else{
		uid = '-1';
	}
	var commendTo = '';
	var status = '';
	var price='';
	var t = "1";
	var s="10";
	var buySum=$("#buyCount").val();
	var remaining=0;
	var caps=0;
	var intervalTime="";
	var intervalId1="";
	
	
	//时间戳转换成日期
	exports.getLocalTime=function(now){ 
		var now=new Date(now);
        var year=now.getFullYear();     
        var month=now.getMonth()+1;     
        var date=now.getDate();     
        var hour=now.getHours();     
        var minute=now.getMinutes();     
        var second=now.getSeconds();   
        var ds=year+"-"+month+"-"+date+" "+hour+":"+minute+":"+second;
        return ds;
        }; 
        

	// 判断用户
	if(uid!="-1"){
		exports.options.userlink = $CONFIG.base_url + "/api/user";
		exports.options.userParams = {
			"uid" : uid
		};
		var userInfor = $.get(exports.options.userlink, exports.options.userParams);
		userInfor.done(function(data) {
			$(".user_name").text(data.user.name);
			if (data.user.roles == "charitarian") {
				$("#recommendProject").css("display", "block");
			}
		});
	}
	//当前日期
	var dqDate = new Date();
	 var vYear = dqDate.getFullYear();
	 var vMon =dqDate.getMonth() + 1;
	 var vDay = dqDate.getDate();
//	 var h = dqDate.getHours(); 
//	 var m = dqDate.getMinutes(); 
//	 var se = dqDate.getSeconds(); 
	 if(vMon<10){
		 s_today = vYear + "-" +vMon + "-"+(vDay < 10 ?vDay +"  ": vDay);
	 }else{
		 s_today = vYear + "-" +vMon + "-"+(vDay < 10 ?vDay +" ": vDay);
	 }
//	today_date = vYear+"-" +(vMon<10 ? "0" + vMon : vMon)+"-" +(vDay<10 ? "0"+ vDay : vDay)+"-" +(h<10 ? "0"+ h : h)+"-" +(m<10 ? "0" + m : m)+"-" +(se<10 ? "0" +se : se);
//	today_date_stamp=today_date.timeStamp;
	//获取统计方法
	exports.getData=function getData(api,cid){
		exports.options.commentlink = $CONFIG.base_url + api;
		exports.options.commentParams = {
			"pid" : pida
		};
		var commentInfor = $.get(exports.options.commentlink, exports.options.commentParams);
		commentInfor.done(function(data) {
			var nDate='';
			var d=[];
			var x=[];
			for(var i=0;i<data.length;i++){
				nDate=exports.getLocalTime(data[i].date);
				nDate=nDate.substring(0,10);
				//var day=parseInt(exports.getLocalTime(data[i].date).substring(8,10));
				point =[i , data[i].count ];
				xpoint=[i,nDate];
				d.push(point);
				x.push(xpoint);
				if(nDate==s_today){
					if(api=="/api/project/statistic/comments"){
						$(".new_incress_comment em").text(data[i].count);
					}else if(api=="/api/project/statistic/attentions"){
						$(".new_incress_attention em").text(data[i].count);
					}else if(api=="/api/project/statistic/shares"){
						$(".new_incress_share em").text(data[i].count);
					}
					else if(api=="/api/project/statistic/supports"){
						$(".new_incress_support em").text(data[i].count);
					}
				}
			}
			exports.flots(d,30,x,cid);
		});
	};
	
	$("#addProjectAd").validate({
		rules : {
			title : {
				required :true,		
			}
		},
	messages : {
		title : {
			required:function(){
				$.jBox.tip('亲~公告标题不能为空！');
			},
		}
	},
	});
	

	//获取关注统计数据
	exports.getData("/api/project/statistic/attentions","attentionTable");
	//获取分享统计数据
	exports.getData("/api/project/statistic/shares","shareTable");
	//获取评论统计数据
	exports.getData("/api/project/statistic/comments","commentsTable");
	//获取资助统计数据
	exports.getData("/api/project/statistic/supports","supportsTable");
	// 表格和柱状图
	exports.flots=function flots(data,days,x,cid){
		var attentionTable = document.getElementById(cid);//关注
//		var shareTable = document.getElementById('shareTable');//分享
//		var supportsTable = document.getElementById('supportsTable');//资助
//		var commentsTable = document.getElementById('commentsTable');//评论

		var horizontal = (horizontal ? true : false);
		data = [ {
			data : data,
		} ];
		var options = {
			colors : [ '#00A8F0', '#C0D800', '#CB4B4B','#4DA74D', '#9440ED' ],
			legend : {
				position : 'nw',
			},
			xaxis : {
				ticks:x,
				title:'日期',
				parseFloat : false,
				minorTickFreq : 4,
//				min : 0,
//				noTicks:days, 
				//max : days,
				autoscaleMargin : 0.5,
				tickFormatter : Flotr.defaultTickFormatter, // 刻度的格式化方式
				tickDecimals : 0,
				margin : true,
				//mode: "time",
				//timeformat: "%y/%m/%d"
			},
			yaxis : {
				min : 0,
				max : 100,
				noTicks : 5,
			},
			bars : {
				show : true,
				horizontal : horizontal,
				shadowSize : 0,
				barWidth : 0.2
			},
			grid : {
				color : '#cccccc', // => 表格外边框和标题以及所有刻度的颜色
				tickColor : '#DDDDDD', // => 表格内部线条的颜色
				verticalLines : true, // => 表格内部是否显示垂直线条

			},
			mouse:{
                track: true,          //  为true时,当鼠标移动到每个折点时,会显示折点的坐标
                trackAll: true,       // 为true时,当鼠标在线条上移动时,显示所在点的坐标
                position: 'se',        // 鼠标事件显示数据的位置 (default south-east)
                sensibility: 2,        // 值越小,鼠标事件越精确
         }
		};
		$('a[data-toggle="tab"]').on('shown', function() {
			Flotr.draw(attentionTable, data, options);
//			Flotr.draw(shareTable, data, options);
//			Flotr.draw(supportsTable, data, options);
//			Flotr.draw(commentsTable, data, options);
		});
	};
	
	// 定时器
	exports.time = function time() {
		t = t - 1;
		if (t < 0) {
			clearInterval(time);
			return false;
		}
		if (t == 0) {
			clearInterval(time);
			$(".letter_send_error").hide();
			$(".letter_send_seccuss").hide();
		}
	};
	// 定时器
	exports.auto_jump = function auto_jump() {
		secs = $(".showbox").first().text()-1;
		intervalTime=secs;
		$(".showbox").text(secs);
		if (secs < 0) {
			return false;
		}
		if (secs == 0) {
			clearInterval(time);
//			$("#tab-part8").hide();
//			$("#tab-part7").show();
			 location.reload() ;
			exports.productsList();
		} else {

		}
	};
	
	//关闭jbox后继续执行定时
	exports.changeLocation = function changeLocation(){
		if(intervalTime==""){
			intervalTime=5;
		}
		intervalTime--;
		if (intervalTime < 0) {
			return false;
		}
		if (intervalTime == 0) {
			clearInterval(intervalId1);
			location.reload() ;
			exports.productsList();
		}
	};

	//added by fudongdong
	//fudongdonguestc@gmail.com

	//加载 评论
	//exports.comment("#discussAll",callback);
	exports.comment = function comment(con,callback) {
		var showCom = new List();
		showCom.options.template = con+"-template";
		showCom.options.container = "#"+con;
		showCom.options.links = {
			"list" : $CONFIG.base_url + '/api/comment/preferential/list'
		};
		showCom.options.params = {
			"id" : pida,
			"p" : 1,
			"s" : s
		};
		showCom.load(function(){
			if(typeof(callback) == "function"){
				callback();
			}
		});
		
	};

	//格式化时间
	exports.format=function(e){
		$("#"+e+" .send_time").each(function(){
			var t=parseInt($(this).text());
			t=$.timeago(exports.getLocalTime(t));
			$(this).text(t);
		});
	};

	//删除评论
	exports.delComment=function(e){
		var postData={"cid":e,"uid":uid};
		$.jBox.tip("正在处理，请稍候...","loading");
		var posting = $.post($CONFIG.base_url + "/api/comment/del", postData);
		posting.done(function(data) {
			//console.log(data);
			if(data.msg == 'true'){
				$.jBox.closeTip();
				$.jBox.tip("删除成功！");
				exports.comment("discussAll");
				exports.comment("projectCommentList");
			}else{
				$.jBox.closeTip();
				$.jBox.tip("对不起您没有权限删除该评论！");
			}
			
		}).fail(function() {
			$.jBox.closeTip();
			$.jBox.tip("删除失败！");
		});
	};

	// 添加回复框
	exports.addChart = function addChart(uid, fid, commendTo) {
		$(this)	.parent().parent().after(
						"<tr><td colspan='4'><div id='chart_diag' class='chart_diag' style='width:100%;'><form id='lerterForm' method=post'><input type='hidden' name='userId' value='"
								+ uid
								+ "'/><input type='hidden' name='superComment.id' value='"
								+ commendTo
								+ "'/><input type='hidden' name='preferential.id' value='"
								+ pida
								+ "'/><input type='hidden' name='commentTo' value='"
								+ fid
								+ "'/><textarea rows='' cols='' name='content' maxlength='100' style='height:80px;width:95%;'></textarea><br /><button class='send_leter color_theme' style='float:none;'>发送</button></form></div></td></tr>");
	};

	exports.submitForm = function submitForm(e, v) {
		if($g_user.login=="false"){
			$.jBox.tip("亲~你还没有登录呢");
			setTimeout(window.location.href=$CONFIG.base_url +"/login",1000); 
		}else if($g_user.login=="true"){
			var json = form2js(e, '.', true);
			var postData = $.toJSON(json);
			$.ajax({
				url : $CONFIG.base_url + v,
				type : "POST",
				data : postData,
				contentType : "application/json",
				success : function(data) {
					if(data.msg=="comment_success"){
						
						$.jBox.tip("评论成功！");
						exports.comment("discussAll",function(e){
							//e.preventDefault();
							exports.format("tab-part2");
						});
						exports.comment("projectCommentList",function(e){
							exports.format("tab-part5");
						});
					}else if(data.msg=="content_is_null"){
						$.jBox.tip("评论失败，请写入评论内容！");
					}
				},
				error : function() {
					$.jBox.tip("评论失败，请重试！");
				}
			});
		}
	};


	// 分享项目
	$("#shareTo").click(function() {
		$(".share").show();
		$(".bdsharebuttonbox a").click(function(){
			$(".share").hide(500);
		});
	});
	$('.close_share').click(function(){
		$(".share").hide();
	});
	$(".share .bdsharebuttonbox a").click(function(){
		var da=new Date().getTime();
		var share=new Object();
		var pid=new Object();
		pid["id"]=pida;
		share["project"]=pid;
		share["userId"]=uid;
		share["platform"]="3";
		share["shareLink"]=$CONFIG.base_url+ "/project/detail" + "?id="+ pida + "&uid=" +uid+ "&date=" + da;
		var postData = $.toJSON(share);
		$.ajax({
			url : $CONFIG.base_url + "/api/project/share",
			type : "POST",
			data : postData,
			// dataType : "json",
			contentType : "application/json",
			success : function() {
				$.jBox.tip("分享成功！");
			},
			error : function() {
				$.jBox.tip("分享失败，请重试！");
			}
		});
	});

	$(document).ready(function(){
	exports.options.projectCoverLink = $CONFIG.base_url
		+ "/api/preferential/get";
	exports.options.projectCoverPageParams = {
	"id" : pida,
	//"uid" : uid
	};
	var activityBack=$.get(exports.options.projectCoverLink,
			exports.options.projectCoverPageParams);
	activityBack.done(function(data){
		var result={};
		result.preferential=data;
		var selectKind1 = template.render(
				'projectCover-template', result);
		$('#projectCover').empty().append(selectKind1);
		
		var selectKind2 = template.render(
				'introduceProject-template', result);
		$('#introduceProject').empty().append(selectKind2);
		
	});
	});

	//added by fudongdong
	//fudongdonguestc@gmail.com
	exports.comment("discussAll",function(){
		exports.format("tab-part2");

	});

	//发起评论
	$(".raise-submit").click(function(e){
		e.preventDefault();
		var obj=new Object();
		obj.id=pida;
		$(".pid").val(pida);
		$(".uid").val(uid);
		$(".u_method").val('1');
		if(uid=="-1"){
			window.location.href=$CONFIG.base_url +"/login";
		}else{
			var json=form2js("startNewComment2",'.',true);
			json=$.toJSON(json);

			$.ajax({
				url:$CONFIG.base_url+"/api/comment",
				contentType:"application/json;charset=UTF-8",
				dataType:'json',
				data:json,
				method:"post",
				success:function(data){
					if(data.msg=="comment_success"){
						
						$.jBox.tip("评论成功！");
						$("#textarea-text2").val("");
						exports.comment("discussAll",function(e){
							//e.preventDefault();
							exports.format("tab-part2");
						});
					}else if(data.msg=="content_is_null"){
						$.jBox.tip("评论失败，请写入评论内容！");
					}
				},
				error:function(){
					$.jBox.tip("评论失败，请重试。！");
				}
			})

		}
	})

	$('#discussAll').on("click",".del_to_list",function(){
		var delId=$(this).attr('data');
		var submit = function (v, h, f) {
		    if (v == 'ok')
		    	exports.delComment(delId);
		    else if (v == 'cancel')
		    return true; //close
		};
		$.jBox.confirm("<span style='text-align:center;width:100%;display:block;color: #834313;'>您确定要删除？</span>", "<span style='text-align:center;width:100%;display:block;color: #834313;'>友情提示</span>", submit);
	});

	// 回复评论
	$("#discussAll").on('click', '.returnMessage', function() {
		if($("#chart_diag").length==0){
			commendTo = $(this).prev().val();
			var fid = $(this).attr("data");
			$("#chart_diag").remove();
			commendTo=fid.substring(fid.indexOf(',')+1,fid.indexOf('}'));
			fid=fid.substring(fid.indexOf('{')+1,fid.indexOf(','));
			exports.addChart.call(this, uid, fid, commendTo);
			$(".send_leter").click(function(e) {
				e.preventDefault();
				exports.submitForm(lerterForm, '/api/comment');
			});
		}else{
			$("#chart_diag").parent().parent().remove();
		}
		
	});




});
